var app = new Vue({
  el: "#app",
  data: {
    filterForm: {
      zone: [],
      title: "",
      is_car_cate: false,
      sell_type: "",
      time: "",
      time_sell: "",
      desc: "",
      is_push: [],
      msg_type: [],
      crm_push_mans: "",
    },
    multipleSelection: [],
    infoTable: {
      list: [],
      total: 0,
      pageNumber: 1,
      pageSize: 10,
      loading: false,
    },
    showDialogDetail: false,
    infoDetail: {},
    showDialogPush: false,
    userGroups: [],
    ungroupedUsers: [],
    formPush: {
      groups: [],
      users: [],
      channels: ["wechat", "app"],
    },
    hasGetCateZone: false,
    cateOption: [],
    zoneOption: [],
    cateProps: { value: "num_id", label: "name", checkStrictly: true },
    zoneProps: {
      value: "code",
      label: "name",
      checkStrictly: true,
      multiple: "true",
    },
    checkAll: false,
    isIndeterminate: false,
    loadingCopy: false,
    pushType: "table", // 推送入口类型，table：表格，detail：详情
    needRestore: false,
  },
  mounted() {
    this.getCateZone();
    this.getInfoList("init");
  },
  methods: {
    // 获取下拉数据
    getCateZone() {
      if (this.hasGetCateZone) {
        return;
      }
      this.hasGetCateZone = true;
      apiGetCateList()
        .then((res) => {
          const removeEmptyChildren = (items) => {
            items.forEach((item) => {
              if (item.children?.length === 0) {
                delete item.children;
              } else if (item.children) {
                removeEmptyChildren(item.children);
              }
            });
          };
          removeEmptyChildren(res.data);
          this.cateOption = res.data;
        })
        .catch((err) => {
          this.$message.error(err && err.msg);
        });
      apiGetZoneList()
        .then((res) => {
          this.zoneOption = [
            {
              code: -1,
              name: "未分配地区",
            },
            {
              code: -2,
              name: "全国",
            },
            ...res.data,
          ];
        })
        .catch((err) => {
          this.$message.error(err && err.msg);
        });
    },
    // 获取列表
    getInfoList(type) {
      if (type !== "init") {
        this.infoTable.pageNumber = 1;
      }
      this.infoTable.loading = true;
      const sendDate = apiGetInfoList({
        pageNumber: this.infoTable.pageNumber,
        pageSize: this.infoTable.pageSize,
        ...this.formatFilterForm(),
      })
        .then((res) => {
          const { data, total } = res;
          this.infoTable.list = data;
          this.infoTable.total = total;
          this.infoTable.loading = false;
          this.$refs.infoTable.doLayout();
          // 恢复选择
          if (this.needRestore) {
            this.needRestore = false;
            const copy = [...this.multipleSelection];
            this.$nextTick(() => {
              copy.forEach((item) => {
                const listItem = this.infoTable.list.find(
                  (i) => i.id === item.id
                );
                if (listItem) {
                  this.$refs.infoTable.toggleRowSelection(listItem, true);
                }
              });
            });
          }
        })
        .catch((err) => {
          this.infoTable.list = [];
          this.infoTable.total = 0;
          this.infoTable.loading = false;
          this.$message.error(err && err.msg);
        });
    },
    // 格式化筛选表单
    formatFilterForm() {
      console.log("formatFilterForm:", this.filterForm);
      const form = {};
      const list = ["zone", "time", "time_sell", "is_car_cate"];

      for (const key in this.filterForm) {
        if (!list.includes(key)) {
          form[key] = this.filterForm[key];
        }
      }
      form.sheng_id = [];
      form.shi_id = [];
      form.zone_id = [];
      form.is_zone_choice = 0;
      if (this.filterForm.zone.length > 0) {
        form.sheng_id = [];
        form.shi_id = [];
        form.zone_id = [];
        form.is_zone_choice = 0;
        let all = false;
        this.filterForm.zone.forEach((item) => {
          if (item[0] === -2) {
            // 全国
            all = true;
          } else if (item[0] === -1) {
            // 未分配地区
            form.is_zone_choice = 1;
          } else {
            const length = item.length;
            if (length === 1) {
              form.sheng_id.push(item[0]);
            } else if (length === 2) {
              form.shi_id.push(item[1]);
            } else if (length === 3) {
              form.zone_id.push(item[2]);
            }
          }
        });
        if (all) {
          form.sheng_id = [];
          form.shi_id = [];
          form.zone_id = [];
          form.is_zone_choice = 0;
        }
      }
      if (this.filterForm.time && this.filterForm.time.length > 0) {
        form.start_time = this.filterForm.time[0];
        form.end_time = this.filterForm.time[1];
      } else {
        form.start_time = "";
        form.end_time = "";
      }
      if (this.filterForm.time_sell && this.filterForm.time_sell.length > 0) {
        form.sell_start_time = this.filterForm.time_sell[0];
        form.sell_end_time = this.filterForm.time_sell[1];
      } else {
        form.sell_start_time = "";
        form.sell_end_time = "";
      }
      form.is_car_cate = this.filterForm.is_car_cate ? 0 : "";
      return form;
    },
    // 重置筛选表单
    resetfilterForm() {
      this.$refs.filterFormRef.resetFields();
      this.filterForm = {
        zone: [],
        title: "",
        is_car_cate: false,
        sell_type: "",
        time: "",
        time_sell: "",
        desc: "",
        is_push: [],
        msg_type: [],
        crm_push_mans: "",
      };
      this.getInfoList();
    },
    // 每页数
    sizeChangeHandle(table, val) {
      this.infoTable.pageSize = val;
      this.infoTable.pageNumber = 1;
      this.getInfoList("init");
    },
    // 当前页
    currentChangeHandle(table, val) {
      this.infoTable.pageNumber = val;
      this.getInfoList("init");
    },
    // 表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 查看详情
    handleDetail(scope) {
      this.infoDetail = {};
      this.showDialogDetail = true;
      this.getInfoDetail(scope.row.id, scope.row.number_id);
    },
    // 获取详情
    getInfoDetail(id, number_id) {
      apiGetInfoDetail({ id, number_id })
        .then((res) => {
          res.data.images =
            res.data.images.length > 0 ? res.data.images.split("|") : [];
          this.infoDetail = res.data;
          let emptyList = ["power_result", "is_push", "images", "video_url"];
          for (let key in this.infoDetail) {
            if (!emptyList.includes(key)) {
              if (
                this.infoDetail[key] === "" ||
                this.infoDetail[key] === null ||
                this.infoDetail[key].ength === 0
              ) {
                this.infoDetail[key] = "无";
              }
            }
          }
        })
        .catch((err) => {
          this.$message.error(err && err.msg);
        });
    },
    // 推送用户
    handlePush(type) {
      this.pushType = type;
      this.showDialogPush = true;
      this.getUserGroups();
    },
    // 复制信息
    handleCopyInfo() {
      this.loadingCopy = true;
      apiGetMiniProgramUrl({
        id: this.infoDetail.id,
        number_id: this.infoDetail.number_id,
      })
        .then((res) => {
          this.loadingCopy = false;
          const textToCopy = `标题: ${this.infoDetail.title}\r所属地区: ${this.infoDetail.city_names}\r开拍日期: ${this.infoDetail.sell_time}\r处置公司: ${this.infoDetail.company_name}\r查看详情: ${res.data.url}`;
          this.copy(textToCopy);
        })
        .catch((err) => {
          this.loadingCopy = false;
          this.$message.error(err && err.msg);
        });
    },
    copy(text) {
      const clipboard = navigator.clipboard || {
        writeText: (text) => {
          return new Promise((resolve, reject) => {
            console.log('document.execCommand("copy")');
            const textarea = document.createElement("textarea");
            textarea.setAttribute("readonly", "readonly");
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            if (document.execCommand) {
              document.execCommand("copy");
              resolve();
            } else {
              reject();
            }
            document.body.removeChild(textarea);
          });
        },
      };
      clipboard
        .writeText(text)
        .then(() => {
          this.$message.success("复制成功");
        })
        .catch((error) => {
          this.$message.error("复制失败: " + error);
        });
    },
    // 修改成交状态
    handleDealStatusChange() {
      apiUpdateDealStatus({
        id: this.infoDetail.id,
        status: this.infoDetail.dealStatus,
      })
        .then((res) => {
          this.$message.success("操作成功");
        })
        .catch((err) => {
          this.$message.error(err && err.msg);
        });
    },
    // 获取用户分组
    getUserGroups() {
      apiGetUserGroups()
        .then((res) => {
          this.userGroups = res.data.groups.map((group) => {
            group.users = group.users.map((user) => {
              return { ...user, isChecked: false };
            });
            return {
              ...group,
              expanded: false,
              isChecked: false,
              isIndeterminate: false,
            };
          });
          console.log("用户分组:", this.userGroups);
          this.ungroupedUsers = res.data.users;
        })
        .catch((err) => {
          this.$message.error(err && err.msg);
        });
    },
    toggleGroupUsers(group) {
      group.expanded = !group.expanded;
    },
    // 选择用户组
    handleCheckGroup(group, val) {
      if (val) {
        group.users.forEach((user) => {
          user.isChecked = true;
        });
      } else {
        group.users.forEach((user) => {
          user.isChecked = false;
        });
      }
      group.isIndeterminate = false;
    },
    // 选择用户
    handleCheckUser(group) {
      console.log("选择用户:", group);
      let count = 0;
      group.users.forEach((user) => {
        if (user.isChecked) {
          count++;
        }
      });
      group.isChecked = count === group.users.length;
      group.isIndeterminate = count > 0 && count < group.users.length;
    },

    handleConfirmPush() {
      this.formPush.groups = [];
      this.userGroups.forEach((group) => {
        let users = [];
        group.users.forEach((user) => {
          if (user.isChecked) {
            users.push(user.id);
          }
        });
        if (users.length > 0) {
          this.formPush.groups.push({
            id: group.id,
            users: users,
          });
        }
      });
      if (
        this.formPush.groups.length === 0 &&
        this.formPush.users.length === 0
      ) {
        this.$message.error("请选择用户");
        return;
      }
      let ids = [];
      let number_ids = [];
      if (this.pushType === "detail") {
        ids = [this.infoDetail.id];
        number_ids = [this.infoDetail.number_id];
      } else {
        this.multipleSelection.forEach((item) => {
          ids.push(item.id);
          number_ids.push(item.number_id);
        });
      }
      apiPushInfo({
        ids,
        number_ids,
        ...this.formPush,
      })
        .then((res) => {
          this.$message.success("推送成功");
          this.showDialogPush = false;
          this.resetFromPush();
          this.getInfoList("init");
          if (this.pushType === "detail") {
            this.needRestore = true;
          }
        })
        .catch((err) => {
          this.$message.error(err && err.msg);
        });
    },
    // 重置推送表单
    resetFromPush() {
      this.formPush = {
        groups: [],
        users: [],
        channels: ["wechat", "app"],
      };
    },
  },
});
